package cn.zto.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.zto.service.JobService;
import cn.zto.vo.PageTrigger;

@Controller
public class SchedulerController {
	
	private boolean init = false;
	
	@Autowired
	private JobService jobService;
	@RequestMapping("/show")
	public ModelAndView show(HttpServletRequest request,HttpServletResponse response){
//		if (!init) {
//			jobService.stopScheduler();
//		}
		List<PageTrigger> triggers = getTriggers(request);
		ModelAndView mv = new ModelAndView();
		mv.addObject("triggers", triggers); 
		mv.setViewName("show");
		mv.addObject("msg", "hello kitty");
		return mv;
		
	}
	
	@RequestMapping("/{name}/{group}/add")
	public String add(@PathVariable String name,@PathVariable String group){
		jobService.add(name,group);
		return "redirect:/show";
	}
	
	@RequestMapping("/{name}/{group}/stop")
	public String stop(@PathVariable String name,@PathVariable String group){
		jobService.stopJob(name, group);
		return "redirect:/show";
	}

	@RequestMapping("/{name}/{group}/del")
	public String del(@PathVariable String name, @PathVariable String group){
		jobService.delJob(name, group);
		return "redirect:/show";
	}

	@RequestMapping("/{name}/{group}/{cron}/modify")
	public String modify(@PathVariable String name, @PathVariable String group ,@PathVariable String cron){
		jobService.modifyTrigger(name, group, cron);
		return "redirect:/show";
	}

	@RequestMapping("/{name}/{group}/startNow")
	public String stratNow(@PathVariable String name, @PathVariable String group){
		jobService.startNowJob(name, group);
		return "redirect:/show";
	}
	
	@RequestMapping("/{name}/{group}/resume")
	public String resume(@PathVariable String name, @PathVariable String group){
		jobService.restartJob(name, group);
		return "redirect:/show";
	}
	
	public List<PageTrigger> getTriggers(HttpServletRequest request){
		List<PageTrigger> triggers = jobService.getTriggersInfo();
		System.out.println(triggers.size());
		request.setAttribute("triggers", triggers);
		return triggers;
	}
	
	
}
